//
//  UIView+cornerRadius.m
//  TravelGuideMdd
//
//  Created by 陈曦 on 13-12-24.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "UIView+cornerRadius.h"
#import <QuartzCore/QuartzCore.h>
#import "NSObject+Associative.h"

static const char UIViewCornerRadius;

@implementation UIView(cornerRadius)



- (CGFloat)cornerRadius
{
    NSNumber *n = [self getAssociativeValue:&UIViewCornerRadius];
    return n.floatValue;
}

- (void)setCornerRadius:(CGFloat)cornerRadius
{
    NSNumber *n = [NSNumber numberWithFloat:cornerRadius];
    [self setRetainNonatomicProperty:n byKey:&UIViewCornerRadius];
    
    CGFloat scale = [UIScreen mainScreen].scale;
    CGPoint center = self.center;
    self.frame = CGRectMake(0,
                            0,
                            scale * self.boundsWidth,
                            scale * self.boundsHeight);
    self.transform = CGAffineTransformIdentity;
    self.transform = CGAffineTransformMakeScale(1/scale , 1/scale);
    self.center = center;
    self.layer.cornerRadius = cornerRadius*scale;
    self.clipsToBounds = YES;
    self.layer.shouldRasterize = YES;
}


- (void)roundCorner:(CGFloat)radius insetWidth:(CGFloat)insetWidth
{
    self.layer.cornerRadius = 0;
    self.layer.masksToBounds = NO;
    
    if (self.layer.mask == nil) {
        CAShapeLayer *mask = [CAShapeLayer layer];
        mask.fillColor = [UIColor blackColor].CGColor;
        mask.shouldRasterize = YES;
        mask.rasterizationScale = 3.0;
        self.layer.mask = mask;
    }
    [(CAShapeLayer *)self.layer.mask setPath:[UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, insetWidth, insetWidth)
                                                                        cornerRadius:radius].CGPath];
}

- (void)roundCornerWithInsetWidth:(CGFloat)insetWidth
{
    [self roundCorner:floorf(self.bounds.size.height/2) insetWidth:insetWidth];
}

- (void)roundCorner:(CGFloat)radius borderColor:(UIColor *)borderColor
{
    return [self roundCorner:radius borderColor:borderColor borderWidth:2];
}

- (void)roundCorner:(CGFloat)radius borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth
{
    if (radius > 0) {
        self.layer.shouldRasterize = YES;
        self.layer.rasterizationScale = [UIScreen mainScreen].scale;
        self.layer.cornerRadius = radius;
        self.layer.masksToBounds = YES;
        self.layer.mask = nil;
    } else {
        self.layer.shouldRasterize = NO;
        self.layer.rasterizationScale = [UIScreen mainScreen].scale;
        self.layer.cornerRadius = 0;
        self.layer.masksToBounds = YES;
        self.layer.mask = nil;
    }
    
    if (borderColor) {
        self.layer.borderColor = borderColor.CGColor;
        self.layer.borderWidth = borderWidth;
    } else {
        self.layer.borderColor = nil;
        self.layer.borderWidth = 0;
    }
}


@end
